/**----------------------------------------
 * @description 下载工具类
 * @author      lxc
 * @file        DownloadMgr.ts
 * @Date        2022-05-05
 * @version     1.0.0
 * ----------------------------------------
 */
import { LogClass } from "./LogClass";

export interface HttpError {
    err_code: number;
    err_content: string;
}

export class DownloadMgr extends LogClass {
    /**
     * 下载器
     */
    protected downloader: jsb.Downloader = null;
    /**
     * 存储下载任务的过程回调函数
     */
    protected taskProgress: Map<string, Function> = new Map();
    /**
     * 存储下载任务成功回调函数,一个结果回调需要处理成功和失败两种情况
     */
    protected taskSuccess: Map<string, Function> = new Map();
    /**
     * 下载任务的出错处理函数
     */
    protected taskError: Map<string, Function> = new Map();

    constructor() {
        super()
        this.initDownloader()
    }

    protected initDownloader() {
        if (CC_JSB) {
            this.downloader = new jsb.Downloader();
            this.downloader.setOnFileTaskSuccess(this.onSucceed.bind(this));
            this.downloader.setOnTaskProgress(this.onProgress.bind(this));
            this.downloader.setOnTaskError(this.onError.bind(this));
        }
    }

    protected onProgress(task: jsb.DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) {
        if (task.identifier) {
            if (this.taskProgress.has(task.identifier)) {
                if (totalBytesExpected != 0) {
                    this.taskProgress.get(task.identifier).apply(null, totalBytesReceived / totalBytesExpected)
                }
            }
        }
    }

    protected onSucceed(task: jsb.DownloaderTask) {
        this.printLog("success :", task.requestURL)
        if (task.identifier) {
            if (this.taskSuccess.has(task.identifier)) {
                this.taskSuccess.get(task.identifier).apply(null, task.storagePath);
            }
        }
    }

    protected onError(task: jsb.DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) {
        this.printError("fail :", task.requestURL)
        if (task.identifier) {
            if (this.taskError.has(task.identifier)) {
                let errorInfo: HttpError = {
                    err_code: errorCode, err_content: errorStr
                }
                this.taskError.get(task.identifier).apply(null, errorInfo);
            }
        }
    }
    /**
     * 创建下载任务执行下载
     * @param url 
     * @param savePath 
     * @param onComplete 
     * @param onProgress 
     */
    downloadFile(url: string, savePath: string, onComplete: Function, onError?: Function, onProgress?: Function) {
        if (CC_JSB) {
            // PackManager
            let identifier = "md5(savePath)"
            this.printLog("download", url)
            // 创建下载任务
            this.downloader.createDownloadFileTask(url, savePath, identifier)

            this.taskSuccess.set(identifier, onComplete);

            if (onError) {
                this.taskError.set(identifier, onError);
            }

            if (onProgress) {
                this.taskProgress.set(identifier, onProgress);
            }
        } else {
            onComplete({ err_code: -1, err_content: "不存在jsb" }, null);
        }
    }
    /**
     * 常用的文件下载方法
     * @param url 
     * @param onComplete 
     * @param replace 
     */
    loadFileByURL(url: string, onComplete: Function, replace?: boolean) {
        let savePath = gVar.Tools.FileTool.getSavePath(url);
        let exists = gVar.Tools.FileTool.fileExists(savePath);
        if (replace && exists) {
            gVar.Tools.FileTool.clearPath(savePath)
            exists = false
        }
        if (exists) {
            onComplete(savePath)
        } else {
            this.downloadFile(url, savePath, onComplete)
        }
    }
}